package com.wuyou.simple;

/**
 * 643. 子数组最大平均数 I
 *
 * @Date 2024/11/29 14:46
 * @Author 无忧
 */
public class FindMaxAverage {

    public static void main(String[] args) {
        int[][] nums = {{0, 1, 1, 3, 3}, {1, 12, -5, -6, 50, 3}, {8860, -853, 6534, 4477, -4589, 8646, -6155, -5577, -1656, -5779, -2619, -8604, -1358, -8009, 4983, 7063, 3104, -1560, 4080, 2763, 5616, -2375, 2848, 1394, -7173, -5225, -8244, -809, 8025, -4072, -4391, -9579, 1407, 6700, 2421, -6685, 5481, -1732, -8892, -6645, 3077, 3287, -4149, 8701, -4393, -9070, -1777, 2237, -3253, -506, -4931, -7366, -8132, 5406, -6300, -275, -1908, 67, 3569, 1433, -7262, -437, 8303, 4498, -379, 3054, -6285, 4203, 6908, 4433, 3077, 2288, 9733, -8067, 3007, 9725, 9669, 1362, -2561, -4225, 5442, -9006, -429, 160, -9234, -4444, 3586, -5711, -9506, -79, -4418, -4348, -5891}};
        int[] k = {4, 4, 93};
        for (int i = 0; i < nums.length; i++) {
            System.out.println(findMaxAverage1(nums[i], k[i]));
        }
    }

    public static double findMaxAverage1(int[] nums, int k) {
        int l = 0, r = 0, sum = 0;
        double max = Integer.MIN_VALUE;
        while (r < k) {
            sum += nums[r++];
        }
        max = sum;
        while (r < nums.length) {
//            sum -= nums[l++];
//            sum += nums[r++];
            // 分开写会多一次赋值
            sum = sum - nums[l++] + nums[r++];
            max = Math.max(sum, max);
        }
        return max / k;
    }

    public static double findMaxAverage(int[] nums, int k) {
        int l = 0, r = 0, count = 0, sum = 0;
        double max = Integer.MIN_VALUE;
        while (r < nums.length) {
            count++;
            if (count < k) {
                sum += nums[r++];
                continue;
            }
            sum += nums[r++];
            max = Math.max(sum, max);
            sum -= nums[l++];
        }
        return max / k;
    }

}
